import moment from 'moment'
import XLSX from 'xlsx'

const BaseItems = [{label: '投递岗位', key: 'positionId', options: []},
    {label: '姓名', key: 'name', cell: 'B1', type: 2},
    {label: '性别', key: 'gender', cell: 'D1', options: [{id: 0, name: '男'}, {id: 1, name: '女'}, {id: 2, name: '未知'}]},
    {label: '生日', key: 'birth', cell: 'F1', type: 1}, {label: '籍贯', cell: 'B2', key: 'nativePlace', type: 2},
    {label: '民族', key: 'nation', cell: 'D2', type: 2}, {label: '职称', cell: 'F2', key: 'positionalTitle', type: 2},
    {label: '政治面貌', cell: 'B3', key: 'politicalIdentity', type: 2}, {label: '身份证号', cell: 'D3', key: 'idNumber', type: 2},
    {label: '最高学历', key: 'education', cell: 'B4', type: 2}, {label: '最高学位', key: 'degree', cell: 'D4', type: 2},
    {label: '毕业时间', key: 'graduationTime', cell: 'F4', type: 1}, {label: '通信地址', cell: 'C5', key: 'address', type: 2},
    {label: '邮编', key: 'postcode', cell: 'H5', type: 2}, {label: '电子邮箱', key: 'email', cell: 'C6', type: 2},
    {label: '手机号码', key: 'phone', cell: 'F6', type: 2}]
const ExtItems = [{label: '工作经历', key: 'work', cell: 'B11'}, {label: '科研成果', key: 'research', cell: 'B12'},
    {label: '培训经历', key: 'train', cell: 'B13'}, {label: '获奖经历', key: 'award', cell: 'B14'},
    {label: '取得资质证书经历', key: 'certificate', cell: 'B15'}, {label: '中远期职业规划', key: 'plan', cell: 'B16'},
    {label: '可承担课程内容', key: 'course', cell: 'B17'}]
const ResumeItems = { BaseItems, ExtItems }

const getInterviewStatusText = (status) => {
    const text = {
        '0': '未安排',
        '1': '待面试',
        '-1': '简历不通过',
        '2': '面试通过',
        '-2': '面试不通过',
        '-3': '对方拒绝面试'
    }
    return text[status] || '未知状态'
}
const getSignStatusText = (status) => {
    const text = {
        '0': '未记录',
        '1': '待签约',
        '-1': '拒绝录用',
        '2': '已签约',
        '-2': '对方拒绝签约'
    }
    return text[status] || '未知状态'
}
const parseTimestamp = (timestamp) => {
    return timestamp ? moment(timestamp).format("YYYY-MM-DD HH:mm:ss") : '-'
}
const parseTimestamp2Birth = (timestamp) => {
    return timestamp ? moment(timestamp).format("YYYY-MM") : ''
}
const parseTimestamp2Date = (str) => {
    return str ? moment(new Date(str)).format("YYYY-MM-DD") : ''
}

const Resume = (data, positionMap, memberMap) => {
    if (!data) return
    data.forEach(item => {
        item.key = item.id
        item.rate = item.numAccept + '/' + item.numEvaluated
        item.position = positionMap[item.positionId]
        item.interviewStatusText = getInterviewStatusText(item.interviewStatus)
        item.signStatusText = getSignStatusText(item.signStatus)
        item.interviewTime = parseTimestamp(item.interviewTime)
        item.signTime = parseTimestamp(item.signTime)
        item.createTime = parseTimestamp(item.createTime)
        item.interviewHandler = item.interviewHandlerId && memberMap ? memberMap[item.interviewHandlerId] : '-'
        item.signHandler = item.signHandlerId && memberMap ? memberMap[item.signHandlerId] : '-'
    })
}

const ResumeState = (data) => {
    const steps = {interview: '面试', sign: '签约'}
    steps.createTime = parseTimestamp(data.createTime)
    if (data.signStatus === 0) {
        if (data.interviewStatus === 0) {
            steps.current = 0
            steps.status = 'process'
        }
        else {
            steps.interview = getInterviewStatusText(data.interviewStatus)
            steps.interviewTime = parseTimestamp(data.interviewTime)
            steps.current = 1
            steps.status = data.interviewStatus > 0 ? 'process' : 'error'
        }
    }
    else {
        steps.sign = getSignStatusText(data.signStatus)
        steps.signTime = parseTimestamp(data.signTime)
        if (data.signStatus === 2) {
            steps.current = 3
            steps.status = 'finish'
        } else {
            steps.current = 2
            steps.status = data.signStatus > 0 ? 'process' : 'error'
        }
    }

    return steps
}

const ResumeExt = (ext) => {
    if (ext) {
        for (let item of ExtItems) {
            ext[item.key] = ext[item.key] && ext[item.key].split('\n') || ['无']
        }
    }
}

const Interview = (data, memberMap) => {
    if (!data) return
    data.forEach((item) => {
        item.key = item.id
        item.date = moment(item.arrangedTime)
        item.time = moment(item.arrangedTime)
        item.arrangedTime = parseTimestamp(item.arrangedTime)
        item.createTime = parseTimestamp(item.createTime)
        item.handlerId = item.handlerId && memberMap ? memberMap[item.handlerId] : '-'
        let interviewers = ''
        for (let i = 0; i < item.members.length; i++) {
            if (i > 0) interviewers += ', '
            interviewers += memberMap[item.members[i]]
        }
        item.interviewers = interviewers
    })
}

const Statistics = (data) => {
    if (!data) return
    const sum = {key: 0, position: '总计', col0: 0, col1: 0, col2: 0, col3: 0, col4: 0}
    let key = 1
    data.forEach((item) => {
        item.key = key++
        for (let i = 0; i < 5; i++) {
            if (item.collect && item.collect.length > i) {
                let key = 'col' + i
                item[key] = item.collect[i]
                sum[key] += item[key]
            }
        }
    })
    data.push(sum)
}

const StudyKeys = ['start', 'end', 'college', 'major', 'research', 'system']
const StudyCols = ['C', 'D', 'E', 'F', 'G', 'H']
const StudyRow = 8

const ResumeImport = (file, callback) => {
    const reader = new FileReader()
    reader.onload = function(e) {
        let workbook = XLSX.read(e.target.result, {type: 'binary'})
        if (!workbook || !workbook.SheetNames || workbook.SheetNames.length === 0) callback(null)
        else {
            let data = {}
            let sheet = workbook.Sheets[workbook.SheetNames[0]]
            //Basic Information
            BaseItems.forEach(item => {
                if (item.cell) {
                    let cell = sheet[item.cell]
                    if (cell) data[item.key] = item.type === 1 ? moment(cell.w) : cell.v
                }
            })
            let ext = {}
            data.ext = ext
            ExtItems.forEach(item => {
                if (item.cell) {
                    let cell = sheet[item.cell]
                    if (cell) ext[item.key] = cell.w
                }
            })
            let study = []
            ext.study = study
            for (let i = 0; i < 3; i++) {
                let item = {}
                for (let j = 0; j < StudyCols.length; j++) {
                    let cell = sheet[StudyCols[j] + (StudyRow + i)]
                    if (cell) item[StudyKeys[j]] = cell.w
                }
                if (item.start && item.end) item.time = [moment(item.start), moment(item.end)]
                study.push(item)
            }
            if (data.gender === '男') data.gender = 0
            else if (data.gender === '女') data.gender = 1
            else data.gender = 2
            callback(data)
        }
    }
    reader.readAsBinaryString(file)
}

const sheet2blob = (sheet, sheetName) => {
    sheetName = sheetName || 'sheet1'
    let workbook = {
        SheetNames: [sheetName],
        Sheets: {}
    }
    workbook.Sheets[sheetName] = sheet
    // 生成excel的配置项
    let wopts = {
        bookType: 'xlsx',
        bookSST: false,
        type: 'binary'
    }
    let wbout = XLSX.write(workbook, wopts)
    let blob = new Blob([s2ab(wbout)], {type:"application/octet-stream"})

    function s2ab(s) {
        let buf = new ArrayBuffer(s.length)
        let view = new Uint8Array(buf)
        for (let i=0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF
        return buf
    }
    return blob
}

const ResumeExport = (data, positionMap) => {
    let aoa = [['姓名', '性别', '籍贯', '出生年月', '本科', null, null, null,'硕士', null, null, null, '博士', null, null, null,'岗位', '电话'],
        [null, null, null, null, '毕业院校', '专业', '学制', '毕业时间', '毕业院校', '专业', '学制', '毕业时间', '毕业院校', '专业', '学制', '毕业时间', null, null]]

    for (let row of data) {
        let arr = []
        arr.push(row.name)
        arr.push(row.gender === 0 ? '男' : '女')
        arr.push(row.nativePlace ? row.nativePlace : '')
        arr.push(parseTimestamp2Birth(row.birth))
        let stu = JSON.parse(row.extJson)
        if (stu && stu.study) {
            stu = stu.study
            for (let i = 0; i < 3; i++) {
                if (i < stu.length) {
                    arr.push(stu[i].college)
                    arr.push(stu[i].major)
                    arr.push(stu[i].system)
                    arr.push(stu[i].time && stu[i].time.length > 1 ? parseTimestamp2Date(stu[i].time[1]) : '')
                }
                else {
                    arr.push('')
                    arr.push('')
                    arr.push('')
                    arr.push('')
                }
            }
        }
        else {
            for (let i = 0; i < 12; i++) arr.push('')
        }
        arr.push(positionMap[row.positionId])
        arr.push(row.phone ? row.phone : '')
        aoa.push(arr)
    }
    let sheet = XLSX.utils.aoa_to_sheet(aoa);
    sheet['!merges'] = [
        {s: {r: 0, c: 0}, e: {r: 1, c: 0}},
        {s: {r: 0, c: 1}, e: {r: 1, c: 1}},
        {s: {r: 0, c: 2}, e: {r: 1, c: 2}},
        {s: {r: 0, c: 3}, e: {r: 1, c: 3}},
        {s: {r: 0, c: 4}, e: {r: 0, c: 7}},
        {s: {r: 0, c: 8}, e: {r: 0, c: 11}},
        {s: {r: 0, c: 12}, e: {r: 0, c: 15}},
        {s: {r: 0, c: 16}, e: {r: 1, c: 16}},
        {s: {r: 0, c: 17}, e: {r: 1, c: 17}}
    ]
    return sheet2blob(sheet)
}

export default { Resume, ResumeImport, ResumeState, ResumeExt, ResumeItems, Interview, Statistics, ResumeExport }
